package com.meihua.workflow.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;

import com.meihua.workflow.constants.Constants;
import com.meihua.workflow.constants.R;
import com.meihua.workflow.global.GlobalFilter;
import com.meihua.workflow.model.SysUser;
import com.meihua.workflow.model.vo.SignInVo;
import com.meihua.workflow.model.vo.UserVo;
import com.meihua.workflow.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class LogController {
    @Resource
    private SysUserService sysUserService;
    @PostMapping("/signIn")
    public R login(@RequestBody SignInVo signInVo){


        String username=signInVo.getUsername();
        String password=signInVo.getPassword();
        if (StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            return R.error("用户名或密码不能为空");
        }

       String token = this.sysUserService.login(username,password);
    // 获取当前会话的 token 值
        System.out.println(StpUtil.getTokenValue());

        // 获取当前`StpLogic`的 token 名称
        System.out.println(StpUtil.getTokenName());

        // 获取指定 token 对应的账号id，如果未登录，则返回 null
        System.out.println(StpUtil.getLoginIdByToken(StpUtil.getTokenValue()));

        // 获取当前会话剩余有效期（单位：s，返回-1代表永久有效）
        System.out.println(StpUtil.getTokenTimeout());

        // 获取当前会话的 token 信息参数
        System.out.println(StpUtil.getTokenInfo());


        return R.success(token);
    }
    @GetMapping("/info")
    public R getUserInfo(@RequestParam("token") String token ){

        String userId = JWTUtil.parseToken(token).getPayload("user_id").toString();
        UserVo sysUser = this.sysUserService.getUserInfo(userId);
        log.info(sysUser.toString());
        return R.success(sysUser);
    }
    @PostMapping("/logout")
    public R logOut(){

        return R.success();
    }
    @GetMapping("/resetToken")
    public R resetToken(){
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("user_id", GlobalFilter.access_token);
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60);
                put("refresh_time", System.currentTimeMillis() + 1000 * 60 * 60 );
            }
        };
        String token = JWTUtil.createToken(map, Constants.KEY_CONSTANTS.getBytes(StandardCharsets.UTF_8));
        return R.success(token);
    }
}
